package app.auto.designer.ints;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;

import app.auto.designer.R;
import app.auto.designer.ActivityBase;
import app.auto.designer.intfs.intf.DelActivity;
import app.auto.designer.intfs.intf.SetParamActivity;
import app.auto.designer.tool.PathUtil;
import app.auto.runner.base.MapAdapter;
import app.auto.runner.base.MapViewConf;
import app.auto.runner.base.intf.JsonUtil;
import app.auto.runner.base.intf.json.JsonToMapUtils;

public class SetIntfInstActivity extends ActivityBase {

    private static final int REQUEST_CODE_DEL = 1;
    Map<String, String> jsonparams = new TreeMap<String, String>();
    private boolean canItemClick = true;
    private AdapterView<?> parent;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auto_http_faces_inst);

        ((ListView) findViewById(R.id.intfs)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (canItemClick) {
                    startActivityForResult(new Intent(view.getContext(), SetParamActivity.class).putExtra("data", JsonToMapUtils.entityToJson((Map) parent.getItemAtPosition(position))), 0);
                }
            }
        });
        //load

        findViewById(R.id.addope).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(v.getContext(), SetParamActivity.class), 0);
            }
        });
        //add
        ((ListView) findViewById(R.id.intfs)).setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SetIntfInstActivity.this.parent = parent;
                SetIntfInstActivity.this.position = position;
                startActivityForResult(new Intent(parent.getContext(), DelActivity.class), REQUEST_CODE_DEL);
                canItemClick = false;
                return false;
            }

        });

        //del
        loadData();

    }

    private void del(AdapterView<?> parent, int position) {
        String name = (String) ((Map) ((MapAdapter) parent.getAdapter()).getItem(position)).get("id");
        rmdAPPCONFKey(name);
        fillToInterfaceView();
        ((MapAdapter) parent.getAdapter()).notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_DEL) {
            canItemClick = true;
            if (data != null) {
                String del = data.getStringExtra("del");
                if (del != null && del.equals("true")) {
                    del();
                }
            }
        } else if (data != null) {
            addTo_APPCONF_(data);
        }

    }

    private void del() {
        del(this.parent, this.position);

    }

    public void loadData() {
        addTo_APPCONF_(new Intent());
    }


    private void addFlag(List list, String namev) {
        for (Object o : list) {
            ((Map) o).put(namev.split("-")[0], namev.split("-")[1]);
        }

    }

    private List delfrom_APPCONF(Set keys) {


        Properties p = new Properties();
        try {
            p.load(new InputStreamReader(new FileInputStream(new File(PathUtil.intf_instpath)), "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
            showToast(e.getMessage());

        }
        String key = null;
        for (Object o : keys) {
            key = o.toString();
            if (key != null) {
                p.remove(key);
            }
        }
        try {
            p.store(new FileOutputStream(new File(PathUtil.intf_instpath)), "add " + key);
        } catch (IOException e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }
        List list = fillToInterfaceView();
        return list;
    }

    @NonNull
    private List fillToInterfaceView() {
        List list = loadAPPCONF_values();
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (((Map) o1).get("idx") == null) {
                    ((Map) o1).put("idx", "0");
                }

                if (((Map) o2).get("idx") == null) {
                    ((Map) o2).put("idx", "0");
                }
                return Integer.parseInt(((Map) o1).get("idx").toString()) - Integer.parseInt(((Map) o2).get("idx").toString());
            }
        });
        MapViewConf.with(getBaseContext()).conf(MapViewConf.with(getBaseContext()).pair("description->description").pair("url->left").pair("type->center").source(R.layout.auto_param_item)).source(list, findViewById(R.id.intfs)).toView();
        return list;
    }


    public static String getIntfConf(String intfid){
        Properties p = new Properties();
        try {
            p.load(new InputStreamReader(new FileInputStream(new File(PathUtil.intf_instpath)), "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return p.get(intfid).toString();
    }

    private List addTo_APPCONF_(Intent data) {

        String resultjson = data.getStringExtra("data");
        String key = data.getStringExtra("key");

        Properties p = new Properties();
        try {
            p.load(new InputStreamReader(new FileInputStream(new File(PathUtil.intf_instpath)), "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }

        if (key == null) {
            for (Object k : p.keySet()) {
                jsonparams.put(k.toString(), p.getProperty(k.toString()));
            }

        } else {
            if (key != null) {
                if (!jsonparams.containsKey(key)) {
                    try {
                        resultjson = new JSONObject(resultjson).put("idx", jsonparams.keySet().size() + "").toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (key != null) {
                jsonparams.put(key, resultjson);
                p.put(key, resultjson);
                try {
                    p.store(new FileOutputStream(new File(PathUtil.intf_instpath)), "add " + key);
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast(e.getMessage());
                }
            }
        }


        List list = fillToInterfaceView();
        return list;
    }

    private List loadAPPCONF_values() {
        List rt = new ArrayList();
        List list = new ArrayList(jsonparams.values());
        for (Object s : list) {
            rt.add(JsonUtil.extractJsonRightValue(s.toString()));
        }
        return rt;
    }

    private void rmdAPPCONFKey(String key) {
        jsonparams.remove(key);

        return;
    }

    public static int getSize(Activity aty, float dip) {
        DisplayMetrics dm = new DisplayMetrics();
        aty.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new Float(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, dm)).intValue();
    }
}
